<?php

namespace XiaoZhuBundle\Controller;

use AdminsBundle\Entity\News;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use XiaoZhuBundle\Entity\UserBasic;
use XiaoZhuBundle\Helper\MyController;
/**
 * @Route("/news")
 */
class NewsController extends MyController
{

    /*快速复制项目通用化配置*/
    private $entity;
    private $entityName = "News";
    private $listKeys = array("id","title","introduction","updateTime","cover","banner");
    private $searchKeys = array("title");
    private $conditionKeys = array("cid","isIndex");
    private $editKeys = array("");
    private $perPage = 10;

    /**
     * @Route("/list", name="listNews")
     */
    public function listNews(Request $request)
    {
        $rep = $this->DB("AdminsBundle:NewsClass");
        if (!$cid = $this->getParamRequired("cid",$request)) {
            $class = $rep->findOneBy(array());
            $cid = $class->getId();
        }
        if (!$page = $this->getParamRequired("page",$request)) {$page = 1;}

        $class = $rep->findOneBy(array("id"=>$cid));
        $listInfo = $this->getLists($page,$this->perPage,$cid);
        $info["classes"] = $this->getAllNewsClass();
        $info["lists"] = $listInfo["data"];
        $info["className"] = $class->getName();
        $info["curId"] = $cid;
        //分页
        $baseUrl = $this->generateUrl("listNews");
        $first_url = "$baseUrl?cid=$cid";
        $info["pagination"] = $this->creatPage($first_url,$baseUrl,$listInfo["total"],$this->perPage);
        return $this->render('@XiaoZhu/news_list.html.twig', $info);
    }

    /**
     * @Route("/{id}", name="showNews")
     */
    public function showNews(News $news)
    {
        $rep = $this->DB("AdminsBundle:NewsClass");
        $class = $rep->findOneBy(array("id"=>$news->getCid()));
        $info["classes"] = $this->getAllNewsClass();
        $info["news"] = $news;
        $info["curId"] = $news->getCid();
        $info["location"] = "小主文苑";
        $info["className"] = $class->getName();
        return $this->render('@XiaoZhu/news.html.twig', $info);
    }

    public function getAllNewsClass()
    {
        $rep = $this->DB("AdminsBundle:NewsClass");
        $pages = $rep->findAll();
        $data = array();
        foreach ($pages as $page) {
            $key = $page->getOrders() * 10000000 + $page->getId();
            $data[$key] = array(
                "id"    => $page->getId(),
                "name"  => $page->getName(),
            );
        }
        ksort($data);
        return $data;
    }


    private function getLists($page,$per_page,$cid="")
    {
        $request = Request::createFromGlobals();
        $txtKeywords = $request->get("txtKeywords");
        $qb = $this
            ->getDoctrine()
            ->getManager()
            ->createQueryBuilder();

        $qb->from( "AdminsBundle:".$this->entityName , $this->entityName );
        if ($txtKeywords) {
            $search = $qb->expr()->orX();
            foreach ( $this->searchKeys as $key ) {
                $search->add( $this->entityName.".$key like :key" );
            }
            $qb->where( $search )->setParameter( "key" , "%$txtKeywords%" );}
        if ( $condition = $request->get("cond") ) {
            foreach ( $condition as $key => $val ) {
                if ( $val == "" || !in_array( $key , $this->conditionKeys ) ) { continue; }
                $qb->andWhere( $this->entityName.".$key = :val" )
                    ->setParameter( "val" , $val );}}
        if ($cid) {
            $qb->andWhere( $this->entityName.".cid = :val" )
            ->setParameter( "val" , $cid );
        }
        $qb->orderBy( $this->entityName.".id" , "DESC" );
        //获取列表数目
        $qb->select( array( "COUNT(".$this->entityName.".id) as num" ) );
        $count = $qb->getQuery()->getSingleResult();
        //获取列表内容
        if ($count["num"] == 0) {
            $lists = array();
        }else{
            foreach ($this->listKeys as $key) {
                $select[] = $this->entityName.".".$key;
            }
            $qb->select($select);
            $qb->setFirstResult( $page * $per_page - $per_page );
            $qb->setMaxResults( $per_page );
            $lists = $qb->getQuery()->getResult();
        }
        return array(
            "total" => isset($count["num"]) ? $count["num"] : 0,
            "data"  => $lists
        );
    }
}
